using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Codes.Models;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.IdentityModel.Tokens;
namespace Codes.Controllers;

public class CoursesController : Controller
{
    private readonly StudentInfoDbContext? _db;
    public CoursesController()
    {
        _db = new StudentInfoDbContext();
    }
    public IActionResult Index(string keyword)
    {
        var Courses=_db.Courses.AsQueryable();
        if(!string.IsNullOrEmpty(keyword)){
            Courses=Courses.Where(x=>x.Coursename.Contains(keyword));
        }
        return View(Courses.ToList());
    }

    public IActionResult Crete()
    {
        return View();
    }


    public IActionResult Delete(int id)
    {
        var Del = _db.Courses.Find(id);
        return View(Del);
    }

    public IActionResult Edit(int id)
    {
        var Edi = _db.Courses.Find(id);
        return View(Edi);
    }
    [HttpPost]
    public IActionResult Edit(Course course)
    {
        var Edi = _db.Courses.Find(course.Id);
        if (Edi != null)
        {
           Edi.Coursename=course.Coursename;
           _db.SaveChanges();
           return RedirectToAction("Index");
        }
        return View(Edi);
    }
    [HttpPost]
    public IActionResult Delete(int id, Course course)
    {
        var Del = _db.Courses.Find(id);
        if (Del != null)
        {
            _db.Courses.Remove(Del);
            _db.SaveChanges();
        }
        return RedirectToAction("Index");  // 改为重定向到列表页
    }

    public IActionResult Create()
    {
        return View();
    }
    [HttpPost]
    public IActionResult Create(Course course)
    {
        if (ModelState.IsValid)
        {
            _db.Courses.Add(course);
            _db.SaveChanges();
            return RedirectToAction(nameof(Index));
        }
        return View(course);



    }
}